import axios from 'axios'; //引入axios

//本地环境用的URL
const URL = process.env.API_HOST; // 当前环境的接口前缀,若执行run dev 返回'/api',若执行run build  返回'http://mallapi.qdama.cn'

let httpService = ''; //请求的域名
var currentHost = location.host; //当前访问的域名

//根据当前访问页面的域名设置对应请求数据的域名
if (currentHost == 'localhost:8081' || currentHost == '172.16.0.77:8081') {
    //   httpService = URL; //本地环境
    httpService = 'http://sitadminapi.qdama.cn'; //测试环境
} else if (currentHost == 'liangshaofeng.gitee.io') {
    httpService = 'http://sitmallapi.qdama.cn'; //测试环境
} else if (currentHost == 'liangshaofeng.gitee.io') {
    httpService = 'http://sitmallapi.qdama.cn'; //生产环境
}

// 创建实例时设置配置的默认值
let http = axios.create({
    baseURL: httpService
});

// 在实例已创建后修改默认值
http.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';

// 添加请求拦截器
http.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    var _accessToken = localStorage.getItem('token')
    let params = {
        accessToken: _accessToken
    };
    config.params = Object.assign(config.params || {}, params);
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
http.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    let data = response.data || {};
    if (data.code == '0') {
        return response.data.data;
    } else if (data.code == undefined) {
        return response.data
    } else if (response.data == '') {
        return response.data;
    } else {
        let tipMessage = {
            code: data.code,
            message: data.message
        }
        return Promise.reject(tipMessage);
    }
}, function (error) {
    // 对响应错误做点什么
    let tipMessage = {
        code: '-1',
        message: '网络或系统错误'
    }
    return Promise.reject(tipMessage);
});

//暴露变量
export {
    http,
    httpService,
    currentHost,
};
